import { Injectable, NotFoundException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { ObjectiveEntity } from "./objective.entity";
import { Repository } from "typeorm";
import { v4 as uuidv4 } from "uuid";
import { IPaginationOptions, paginate } from "nestjs-typeorm-paginate";

@Injectable()
export class ObjectiveService {
  constructor(
    @InjectRepository(ObjectiveEntity)
    private readonly objectiveModel: Repository<ObjectiveEntity>
  ) {}

  public async pageQuery(params: any) {
    const {
      skip,
      take,
      sortBy = "createdAt",
      descending = "DESC",
      ...where
    } = params;
    const q = this.objectiveModel.createQueryBuilder("t");
    q.where(where);
    q.addOrderBy(`t.${sortBy}`, descending ? "DESC" : "ASC");
    const options: IPaginationOptions = { limit: take, page: skip };
    return paginate<any>(q, options);
  }

  /**
   * 通过 ID 删除 Entity
   * @param id
   */
  public async removeById(id: string) {
    const tasks = await this.objectiveModel.findOne({ id });
    if (!tasks) {
      throw new NotFoundException();
    }

    await this.objectiveModel.remove([tasks]);
    return true;
  }

  /**
   * 更新数据
   * @param updateEntity
   */
  public async update(updateEntity) {
    const tasks = await this.objectiveModel.findOne({
      id: updateEntity.id,
    });
    if (!tasks) {
      throw new NotFoundException();
    }

    await this.objectiveModel.update({ id: updateEntity.id }, updateEntity);
    return true;
  }

  /**
   * 添加数据
   * @param insertEntity
   */
  public async insert(insertEntity) {
    insertEntity.id = uuidv4();
    insertEntity.createdAt = new Date();
    insertEntity.updatedAt = new Date();
    await this.objectiveModel.insert(insertEntity);
    return true;
  }

  public async batchRemove(ids: string[]) {
    const models = await this.objectiveModel.findByIds(ids);
    await this.objectiveModel.remove(models);
    return true;
  }
}
